#!/usr/bin/env python
version = "Alpha 3 (AKA Damavand)"
import pygeo
import gtk as gtk
from matplotlib.backends.backend_gtkagg import FigureCanvasGTK
from matplotlib.backends.backend_gtkagg import NavigationToolbar2GTKAgg as NavigationToolbarGTK
class Select_window():
	def ok_clicked(self, *args):
		l = []
		item = self.selected_LS.get_iter_first ()

		while ( item != None ):
			l.append (self.selected_LS.get_value (item, 0))
			item = self.selected_LS.iter_next(item)

		self.prop = l
		self.win.hide()
	def remove_clicked(self, *args):
		self.selected2 = self.treeview2.get_selection()
		self.selected2.set_mode(gtk.SELECTION_MULTIPLE)
		(model, pathlist) = self.selected2.get_selected_rows()
		iters=[]
		for path in pathlist:
			iters.append(self.selected_LS.get_iter(path))

		for i in iters:
			if i is not None:
				self.selected_LS.remove(i)


	def add_clicked(self, *arg):

		self.selected = self.treeview.get_selection()
		self.selected.set_mode(gtk.SELECTION_MULTIPLE)
		(model, pathlist) = self.selected.get_selected_rows()
		l = []
		if self.textbox.get_text() <> "" :
			l.append(self.textbox.get_text())
		for path in pathlist:
			tree_iter = model.get_iter(path)
			value = model.get_value(tree_iter, 0)
			l.append(value)

		for i in l:
			self.selected_LS.append([i])

	def __init__(self, data):
		self.prop = []
		self.win = gtk.Window(gtk.WINDOW_TOPLEVEL)
		self.win.set_size_request(500, 700)
		self.win.set_title("Select")
		self.win.set_position(gtk.WIN_POS_CENTER)
		self.LS = gtk.ListStore(str)
		self.selected_LS = gtk.ListStore(str)

		self.data = data
		try:
			for i in self.data:
				iter = self.LS.append([i])
		except:
			pass

		self.treeview = gtk.TreeView()
		self.treeview.set_model(self.LS)
		self.tree_column = gtk.TreeViewColumn("Genes")
		self.treeview.append_column(self.tree_column)
		self.treeview.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
		self.cell_renderer = gtk.CellRendererText()
		self.tree_column.pack_start(self.cell_renderer, True)
		self.tree_column.add_attribute(self.cell_renderer, "text", 0)

		self.vbox = gtk.VBox()

		self.hbox = gtk.HBox()
		self.textbox = gtk.Entry()
		self.vbox.pack_start(self.textbox,False,False)
		self.vbox.pack_start(self.hbox)



		self.scrolled = gtk.ScrolledWindow()
		self.scrolled.add_with_viewport(self.treeview)
		self.hbox.pack_start(self.scrolled)
		self.add_button = gtk.Button("Add ->")
		self.add_button.connect("clicked", self.add_clicked)
		self.remove_button = gtk.Button("<- Remove")
		self.remove_button.connect("clicked", self.remove_clicked)
		self.vbox2 = gtk.VBox()

		self.hbox.pack_start(self.vbox2)
		self.treeview2 = gtk.TreeView()
		self.scrolled2 = gtk.ScrolledWindow()
		self.scrolled2.add_with_viewport(self.treeview2)
		self.treeview2.set_model(self.selected_LS)
		self.tree_column2 = gtk.TreeViewColumn("Selected")
		self.treeview2.append_column(self.tree_column2)
		self.treeview2.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
		self.cell_renderer2 = gtk.CellRendererText()
		self.tree_column2.pack_start(self.cell_renderer2, True)
		self.tree_column2.add_attribute(self.cell_renderer2, "text", 0)

		self.hbox.pack_start(self.scrolled2)


		self.vbox2.pack_start(self.add_button, expand = True,fill = False)
		self.vbox2.pack_start(self.remove_button, expand = True,fill = False)


		self.ok_button = gtk.Button("OK")
		self.ok_button.connect("clicked", self.ok_clicked)
		self.vbox.pack_start(self.ok_button, False)

		self.win.add(self.vbox)


		self.win.connect('delete-event', lambda w, e: w.hide() or True)

	def show(self):
		self.win.show_all()


class Gui():
	def selectg(self, *args):
		self.select_genes_win.show()


	def selects(self, *args):
		self.select_samples_win.show()

	def render_fig(self, *args):

		if  len(self.select_genes_win.prop) > 0 and len(self.select_samples_win.prop) > 0:
			if self.canvas <> None:
				self.viewport.remove(self.canvas)
				self.viewport2.remove(self.tool)

			self.canvas = None
			self.tool = None
			self.canvas = FigureCanvasGTK(self.g.get_plot(self.select_genes_win.prop, self.select_samples_win.prop))
			self.canvas.show()
			self.viewport.add(self.canvas)
			self.tool = NavigationToolbarGTK(self.canvas, self.window)
			self.viewport2.add(self.tool)
	def do_events(self):
		while gtk.events_pending():
			gtk.main_iteration()

	def show_loading(self,boo):
		if boo:
			self.loadingwindow.show_all()
		else:
			self.loadingwindow.hide()
		self.do_events()
	def open_file(self, *args):

		start = False
		chooser = gtk.FileChooserDialog(title="Open a soft file", action=gtk.FILE_CHOOSER_ACTION_OPEN,
		                                buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK, gtk.RESPONSE_OK))

		#recent = gtk.recent_manager_get_default()
		#recent.purge_items()

		if chooser.run() == gtk.RESPONSE_OK:
			file_name = chooser.get_filename()
			chooser.destroy()
			self.do_events()
			start = True
		else :
			chooser.destroy()
			self.show_loading(False)

		if start:
			self.purge_all()
			self.show_loading(True)
			self.do_events()
			self.prog.set_text("Loading")
			self.prog.pulse()
			self.prog.set_pulse_step(.1)
			self.do_events()
			self.p = pygeo.Soft(file_name, verbose=False    )
			i=0
			self.prog.set_pulse_step(.1)
			for x in  self.p.parse2():
				self.prog.set_text("Loading %s" % x)
				self.prog.pulse()
				self.do_events()
			self.prog.set_text("Finalizing...")
			self.prog.pulse()
			self.do_events()
			self.g = pygeo.Graph(self.p)
			self.prog.pulse()
			self.do_events()

			self.select_genes_win = Select_window(self.p.get_genes())
			self.prog.pulse()
			self.do_events()
			self.select_samples_win = Select_window(self.p.list_of_samples)
			self.prog.pulse()
			self.do_events()
			self.select_genes.set_sensitive(True)
			self.select_samples.set_sensitive(True)
			self.render.set_sensitive(True)
			self.show_loading(False)

	def open_about(self, *args):
		self.aboutwindow.run()
	def info_open(self, *args):

		l1 = gtk.Label("Series Title: %s" % self.p.series_title)
		l2 = gtk.Label("Series Accession No: %s" % self.p.series_ano)
		l3 = gtk.Label("Platform Title: %s" % self.p.platform_title)
		l4 = gtk.Label("Organism: %s" % self.p.platform_organism)

		infobox1 = self.wTree.get_object("infobox1")

		for  i in infobox1.get_children():
			infobox1.remove(i)


		infobox1.pack_start(l1)
		infobox1.pack_start(l2)
		infobox1.pack_start(l3)
		infobox1.pack_start(l4)

		self.infowindow.show_all()
	def purge_all(self):
		#del (self.p)
		#del (self.g)
		#del (self.select_genes_win)
		#del (self.select_samples_win)

		self.p = None
		self.g = None
		self.select_genes_win =None
		self.select_samples_win = None

	def __init__(self):
		self.p = None
		self.g = None
		#self.select_genes_win = Select_window(None)
		#self.select_samples_win = Select_window(None)

		self.gladefile = "gui.ui"

		self.wTree = gtk.Builder()
		self.wTree.add_from_file(self.gladefile)
		# Loading the Windows
		self.window = self.wTree.get_object("mainwindow")
		self.aboutwindow = self.wTree.get_object("aboutdialog1")
		self.infowindow = self.wTree.get_object("infowindow")
		self.prog=  self.wTree.get_object("progressbar1")
		self.loadingwindow = self.wTree.get_object("window2")
		self.loadingwindow.show_all()
		self.loadingwindow.hide()
		self.aboutwindow.set_version(version)
		self.aboutwindow.connect('delete-event', lambda w, e: w.hide() or True)
		self.aboutwindow.connect("response", lambda d, r: d.hide())
		self.infowindow.connect("delete-event", lambda w, e: w.hide() or True)
		self.toolbar = self.wTree.get_object("toolbar1")# self.wTree.get_widget("toolbar1")
		self.window.connect("destroy", gtk.mainquit)
		self.window.show_all()
		self.vbox = self.wTree.get_object("vbox2")
		self.viewport = self.wTree.get_object("viewport1")
		self.viewport2 = self.wTree.get_object("viewport2")
		self.open = self.wTree.get_object("open")
		self.about = self.wTree.get_object("about")
		self.info_button = self.wTree.get_object("info")
		self.about.connect("clicked", self.open_about)
		self.open.connect("clicked", self.open_file)
		self.info_button.connect("clicked", self.info_open)
		self.canvas = None
		self.select_genes = self.wTree.get_object("select_genes")
		self.select_samples = self.wTree.get_object("select_samples")
		self.render = self.wTree.get_object("render")
		self.render.connect("clicked", self.render_fig)
		self.select_genes.connect("clicked", self.selectg)
		self.select_samples.connect("clicked", self.selects)
		# disable buttons
		self.select_genes.set_sensitive(False)
		self.select_samples.set_sensitive(False)
		self.render.set_sensitive(False)

gui = Gui()
#select_genes_win = Select_window()
#select_samples_win = Select_window()
gtk.main()